package com.zhinong.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class VoiceRecognitionService {

    private static final String APPID = "8eca6d5d"; // 替换为你的appid
    private static final String API_KEY = "OTI3YmNmMGUzMTQxN2YwMDA1MjJkNTJj"; // 替换为你的api_key
    private static final String SECRET_KEY = "090f9653a956f59badf2338bd8fb64a5"; // 替换为你的secret_key

    public Map<String, Object> uploadVoiceFileAndRecognize(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取上传的语音文件
            Part filePart = request.getPart("voiceFile");
            File uploadedFile = convertPartToFile(filePart);

            // 生成请求参数
            String xParam = generateXParam();
            String xCheckSum = generateXCheckSum(xParam);
            String xCurTime = String.valueOf(System.currentTimeMillis() / 1000L);

            // 调用科大讯飞语音识别接口
            String response = sendVoiceToXunfei(uploadedFile, xParam, xCheckSum, xCurTime);

            // 处理返回结果
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> responseMap = mapper.readValue(response, Map.class);
            String recognitionResult = (String) ((Map<String, Object>) responseMap.get("data")).get("result");
            result.put("result", recognitionResult);

        } catch (IOException | ServletException e) {
            result.put("error", e.getMessage());
        }

        return result;
    }

    private String generateXParam() {
        // 根据科大讯飞文档生成X-Param
        Map<String, Object> param = new HashMap<>();
        param.put("engineType", "sms16k");
        param.put("voiceFormat", "wav");
        param.put("sampleRate", 16000);
        // 其他参数根据需求添加

        String paramJson = new JSONObject(param).toString();
        return Base64.getEncoder().encodeToString(paramJson.getBytes());
    }

    private String generateXCheckSum(String xParam) {
        long curTime = System.currentTimeMillis() / 1000L;
        String strToSign = API_KEY + curTime + xParam;
        return DigestUtils.md5Hex(strToSign);
    }

    private String sendVoiceToXunfei(File file, String xParam, String xCheckSum, String xCurTime) throws IOException {
        String url = "https://api.xfyun.cn/v1/service/cloud/srspeechtranscriber/v1.0/transcriber/batch";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求头部
        con.setRequestMethod("POST");
        con.setRequestProperty("X-Appid", APPID);
        con.setRequestProperty("X-CurTime", xCurTime);
        con.setRequestProperty("X-Param", xParam);
        con.setRequestProperty("X-CheckSum", xCheckSum);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // 设置音频文件数据
        String boundary = "Boundary-" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        // 构建请求体
        StringBuilder sb = new StringBuilder();
        sb.append("--").append(boundary).append("\r\n");
        sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"audio.wav\"\r\n");
        sb.append("Content-Type: audio/wav\r\n\r\n");

        byte[] fileBytes = Files.readAllBytes(file.toPath());
        byte[] fileData = (sb.toString() + new String(fileBytes, "ISO-8859-1") + "\r\n--" + boundary + "--\r\n").getBytes("ISO-8859-1");

        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(fileData);
        wr.flush();
        wr.close();

        // 获取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        con.disconnect();

        return content.toString();
    }

    private File convertPartToFile(Part part) throws IOException, ServletException {
        File file = File.createTempFile("temp", ".wav");
        part.write(file.getAbsolutePath());
        return file;
    }
}